/**
 * IndexedColumn.java
 * Copyright (C) 2011 Yuanyan<yuanyan.cao@gmail.com>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */
package edu.rabbit.kernel.schema;

import org.antlr.runtime.tree.CommonTree;

import edu.rabbit.schema.IIndexedColumn;
import edu.rabbit.schema.SortingOrder;

/**
 * @author Yuanyan<yanyan.cao@gmail.com>
 * 
 */
public class IndexedColumn implements IIndexedColumn {

    private final String name;
    private final String collation;
    private final SortingOrder sortingOrder;

    public IndexedColumn(CommonTree ast) {
        name = ast.getText();
        String collation = null;
        SortingOrder sortingOrder = null;
        for (int i = 0; i < ast.getChildCount(); i++) {
            CommonTree child = (CommonTree) ast.getChild(i);
            if ("collate".equalsIgnoreCase(child.getText())) {
                collation = child.getChild(0).getText();
            } else if ("asc".equalsIgnoreCase(child.getText())) {
                sortingOrder = SortingOrder.ASC;
            } else if ("desc".equalsIgnoreCase(child.getText())) {
                sortingOrder = SortingOrder.DESC;
            } else {
                assert false;
            }
        }
        this.collation = collation;
        this.sortingOrder = sortingOrder;
    }

    public String getName() {
        return name;
    }

    public String getCollation() {
        return collation;
    }

    public SortingOrder getSortingOrder() {
        return sortingOrder;
    }

    @Override
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append(getName());
        if (getCollation() != null) {
            buffer.append(" COLLATE ");
            buffer.append(getCollation());
        }
        if (getSortingOrder() != null) {
            buffer.append(' ');
            buffer.append(getSortingOrder());
        }
        return buffer.toString();
    }
}
